const express = require('express');
const { authenticateToken } = require('../middleware/auth');
const { query } = require('../config/database');
const NotificationService = require('../services/notificationService');

const router = express.Router();

// 获取通知服务实例
let notificationService = null;
const getNotificationService = (io, userSockets) => {
  if (!notificationService && io && userSockets) {
    notificationService = new NotificationService(io, userSockets);
  }
  return notificationService;
};

// 获取通知列表
router.get('/list', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户的通知消息
    const notifications = await query(
      `SELECT id, title, summary, content, type, is_read, created_at
       FROM notifications 
       WHERE user_id = ? 
       ORDER BY created_at DESC 
       LIMIT 50`,
      [userId]
    );

    res.json({
      success: true,
      data: notifications
    });
  } catch (error) {
    console.error('获取通知列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取通知列表失败' 
    });
  }
});

// 标记通知为已读
router.put('/read/:id', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const notificationId = req.params.id;

    await query(
      'UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?',
      [notificationId, userId]
    );

    res.json({
      success: true,
      message: '通知已标记为已读'
    });
  } catch (error) {
    console.error('标记通知已读失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '标记通知已读失败' 
    });
  }
});

// 创建通知
router.post('/create', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { title, content, summary, type = 'info' } = req.body;

    if (!title || !content) {
      return res.status(400).json({
        success: false,
        message: '标题和内容不能为空'
      });
    }

    // 使用通知服务创建并推送通知
    const io = req.app.get('io');
    const userSockets = req.app.get('userSockets');
    const notificationService = getNotificationService(io, userSockets);
    const result = await notificationService.sendNotification(userId, {
      title,
      content,
      summary: summary || content.substring(0, 100) + '...',
      type
    });

    res.json({
      success: true,
      message: '通知创建成功',
      data: result
    });
  } catch (error) {
    console.error('创建通知失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '创建通知失败' 
    });
  }
});

// 创建测试通知
router.post('/create-test', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 创建一些测试通知
    const testNotifications = [
      {
        title: '欢迎使用LinkMate！',
        summary: '开始您的学习之旅！',
        content: '欢迎来到LinkMate学习平台，开始您的学习之旅吧！',
        type: 'system'
      },
      {
        title: '学习提醒',
        summary: '快来制定学习计划！',
        content: '您今天还没有开始学习，快来制定学习计划吧！',
        type: 'task_reminder'
      },
      {
        title: '成就解锁',
        summary: '获得"坚持学习者"徽章！',
        content: '恭喜！您已连续学习7天，获得"坚持学习者"徽章！',
        type: 'achievement'
      },
      {
        title: '好友申请',
        summary: '张三向您发送了好友申请',
        content: '张三向您发送了好友申请，快去查看吧！',
        type: 'friend_request'
      },
      {
        title: '新消息',
        summary: '您收到了一条新的聊天消息',
        content: '您收到了一条新的聊天消息，点击查看详情。',
        type: 'message'
      }
    ];

    // 使用通知服务创建并推送测试通知
    const io = req.app.get('io');
    const userSockets = req.app.get('userSockets');
    const notificationService = getNotificationService(io, userSockets);
    const results = [];
    
    for (const notification of testNotifications) {
      const result = await notificationService.sendNotification(userId, notification);
      results.push(result);
    }

    res.json({
      success: true,
      message: '测试通知创建成功',
      count: testNotifications.length
    });
  } catch (error) {
    console.error('创建测试通知失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '创建测试通知失败' 
    });
  }
});

// 删除通知
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const notificationId = req.params.id;

    await query(
      'DELETE FROM notifications WHERE id = ? AND user_id = ?',
      [notificationId, userId]
    );

    res.json({
      success: true,
      message: '通知删除成功'
    });
  } catch (error) {
    console.error('删除通知失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '删除通知失败' 
    });
  }
});

// 获取未读通知数量
router.get('/unread-count', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    const result = await query(
      'SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE',
      [userId]
    );

    res.json({
      success: true,
      data: { count: result[0].count }
    });
  } catch (error) {
    console.error('获取未读通知数量失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取未读通知数量失败' 
    });
  }
});

// 全部标记为已读
router.put('/mark-all-read', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    await query(
      'UPDATE notifications SET is_read = TRUE WHERE user_id = ? AND is_read = FALSE',
      [userId]
    );

    res.json({
      success: true,
      message: '所有通知已标记为已读'
    });
  } catch (error) {
    console.error('批量标记已读失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '批量标记已读失败' 
    });
  }
});

// 全部删除
router.delete('/delete-all', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    const result = await query(
      'DELETE FROM notifications WHERE user_id = ?',
      [userId]
    );

    res.json({
      success: true,
      message: `已删除 ${result.affectedRows} 条通知`
    });
  } catch (error) {
    console.error('批量删除失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '批量删除失败' 
    });
  }
});

// 获取通知详情 - 必须放在最后，避免与其他路由冲突
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const notificationId = req.params.id;

    const notifications = await query(
      'SELECT * FROM notifications WHERE id = ? AND user_id = ?',
      [notificationId, userId]
    );

    if (notifications.length === 0) {
      return res.status(404).json({
        success: false,
        message: '通知不存在'
      });
    }

    // 自动标记为已读
    await query(
      'UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?',
      [notificationId, userId]
    );

    res.json({
      success: true,
      data: {
        ...notifications[0],
        is_read: true
      }
    });
  } catch (error) {
    console.error('获取通知详情失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '获取通知详情失败' 
    });
  }
});

module.exports = router;